package com.lishe.lishe.lishe.module.pay.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.myorder.activity.MyOrdersActivity;
import com.lishe.lishe.lishe.module.myorder.bean.BusinessObject;
import com.lishe.lishe.lishe.module.myorder.bean.OrderObject;
import com.lishe.lishe.lishe.module.pay.http.HttpPay;
import com.lishe.lishe.lishe.module.recharge.activity.RechargeIntegralActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.lishe.widget.InputDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lwa on 2017/8/23.
 */

public class PayActivity extends BaseActivity implements View.OnClickListener {

    private Button btnBack;
    private Button btnPay;
    private Button btnCancle;
    private TextView title;
    private TextView orderNo;
    private TextView orderCreateTime;
    private TextView orderMoney;
    private TextView remianMoney;
    private TextView recharge;
    private OrderObject orderObject;
    private String remainMoney = "";
    private String token;

    public static void jump(Activity activity, OrderObject orderObject) {
        Intent intent = new Intent(activity, PayActivity.class);
        intent.putExtra("orderObject", orderObject);
        activity.startActivity(intent);
    }

    public static void jump(Activity activity, OrderObject orderObject, int requse_code) {
        Intent intent = new Intent(activity, PayActivity.class);
        intent.putExtra("orderObject", orderObject);
        activity.startActivityForResult(intent, requse_code);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        token = Globals.getToken();
        orderObject = (OrderObject) getIntent().getSerializableExtra("orderObject");
        setContentView(R.layout.activity_pay);
        init();
        RequestParams params = new RequestParams();
        try {
            HttpUserCenter.getUserInfo(params, resposeUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 视图
     */
    private void init() {
        btnBack = findViewById(R.id.title_left_button);
        btnPay = findViewById(R.id.btn_common_blue);
        btnCancle = findViewById(R.id.btn_common_cancle);
        title = findViewById(R.id.title_text_title);
        orderNo = findViewById(R.id.order_no);
        orderCreateTime = findViewById(R.id.order_create_time);
        orderMoney = findViewById(R.id.order_money);
        remianMoney = findViewById(R.id.remian_money);
        recharge = findViewById(R.id.recharge);
        title.setText(R.string.lishe_counter);
        btnPay.setText(R.string.pay_sure);
        initData();
        setListener();
    }

    /**
     * 订单数据初始化
     */
    private void initData() {
        if (orderObject != null) {
            orderNo.setText(orderObject.getPayment_id());
            orderCreateTime.setText(orderObject.getCreated_time());
//            if(orderObject.getMoney()<=0){
//                String str=(int)((float)orderObject.getBusinessTotalMoney()*100 )+ "";
//                orderMoney.setText((int)((float)orderObject.getBusinessTotalMoney()*100 )+ "");
//            }else{
//                String str=(int)((float)orderObject.getBusinessTotalMoney()*100 )+ "";
//                orderMoney.setText(str);
//            }
            String str = String.format("%.0f", (orderObject.getMoney() * 100));
            orderMoney.setText(str);
            remianMoney.setText(remainMoney);
        }
    }

    /**
     * 监听
     */
    private void setListener() {
        btnBack.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        btnCancle.setOnClickListener(this);
        recharge.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.btn_common_blue://付款按钮
                showInputDialog();
                break;
            case R.id.btn_common_cancle://取消按钮
                finish();
                break;
            case R.id.recharge:
                RechargeIntegralActivity.jump((Activity) context);
                break;
        }
    }

    /**
     * 支付接口
     */
    class OrderPay extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            LoadingUtils.createLoadingDialog(PayActivity.this, getString(R.string.paying), false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected String doInBackground(String... strings) {
            HttpPay.orderPay(token, orderObject.getPayment_id(), strings[0], response);
            return null;
        }
    }

    AsyncHttpResponseHandler response = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            LoadingUtils.closeDialog();
            String result = new String(responseBody);
            Log.e("支付结果", result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                JSONObject data = jsonObject.optJSONObject("data");
                String msg = jsonObject.optString("msg");
                if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                    msg = data.optString("msg");
                    showSelectdialog();
                }
                toast(msg);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            toast(getString(R.string.network_or_server_exception));
        }
    };

    /**
     * 密码输入
     */
    private void showInputDialog() {
        InputDialog.Builder dialog = new InputDialog.Builder(this);
        dialog.setTitle(getString(R.string.pls_input_password));
        dialog.setContentHint(getString(R.string.pls_input_pay_paw));
        dialog.setIsShow(false);
        dialog.setPositiveButton(getString(R.string.pay_sure), new InputDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(InputDialog dialog, String content) {
                if (TextUtils.isEmpty(content)) {
                    toast(getString(R.string.pls_input_password));
                } else {
                    dialog.dismiss();
                    new OrderPay().execute(content);
                }
            }
        });
        dialog.setNegativeButton(getString(R.string.cancle_pay), null);
        dialog.show();
    }

    /**
     * 支付成功后dialog
     */
    private void showSelectdialog() {
        ConfirmDialog.Builder dialog = new ConfirmDialog.Builder(this);
        dialog.setContent(getString(R.string.pay_success));
        dialog.setPositiveButton(getString(R.string.go_shopping), new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {//跳到商城
                Intent intent=new Intent(Globals.ACTION_FINISH_ALL_ACTIVITY);
                sendBroadcast(intent);
                MainActivity0.jump(PayActivity.this);
            }
        });

        dialog.setNegativeButton(getString(R.string.see_order), new ConfirmDialog.Builder.OnNegativeListener() {
            @Override
            public void onNegative(ConfirmDialog dialog) {
                for (BusinessObject businessObject : orderObject.getTrade_paybillData()) {//改成已支付状态
                    businessObject.getTradeData().setStatus("WAIT_SELLER_SEND_GOODS");
                }
//                OrderDetailsActivity.jump(PayActivity.this,orderObject);
                MyOrdersActivity.jump(PayActivity.this, Globals.ORDER_TYPE_WAIT_SEND);
                finish();
            }
        });
        dialog.show();
    }

    AsyncHttpResponseHandler resposeUser = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
            LoadingUtils.closeDialog();
            String result = new String(bytes);
            try {
                JSONObject jsonObject = new JSONObject(result);
                String msg = jsonObject.optString("msg");
                if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                    JSONObject dataObject = jsonObject.optJSONObject("data");
                    JSONObject userInfo = dataObject.optJSONObject("userInfo");
                    remainMoney = userInfo.optString("balance");
                    remianMoney.setText(remainMoney + "");
                } else {
                    toast(msg);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast(context.getString(R.string.network_or_server_exception));
            LoadingUtils.closeDialog();
        }
    };
}
